package com.elvin.platform.controller;

import com.elvin.platform.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@RestController
@RequestMapping("/fileUploadController")
@Api("文件上传")
public class FileUploadController {

  private static  String  filePath = "/usr/javaserver/elvinPlatform/uploadFile/";

  private static String domainName = "https://ecmp.elviniot.net/";
  //POST请求接口为/upload
  @ApiOperation(value = "多文件上传")
  @ApiIgnore
  @PostMapping(value = "/uploadFiles", produces = "application/json;charset=utf-8")
  @ResponseBody
  //@RequestParam指向前端input file的name,加入HttpServletRequest请求
  public Result<Object> uploadFiles(@RequestParam("uploadFile") MultipartFile[] multipartFiles, HttpServletRequest request){
    Result<Object> result = new Result<>();
    //设置当前日期
    String uploaddate= new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    //设置文件上传保存文件路径：保存在项目运行目录下的uploadFile文件夹+当前日期
    String savepath = request.getSession().getServletContext().getRealPath("/uploadFile/")+uploaddate;
    //创建文件夹,当文件夹不存在时，创建文件夹
    File folder = new File(savepath);
    if(!folder.isDirectory()){
      folder.mkdir();
    }
    //建立一个listmap的返回参数
    List<Map<String,Object>> listmap =new ArrayList<>();
    //建立一个循环分别接收多文件
    for(MultipartFile file:multipartFiles){
      //重命名上传的文件,为避免重复,我们使用UUID对文件分别进行命名
      String oldName=file.getOriginalFilename();//getOriginalFilename()获取文件名带后缀
      //UUID去掉中间的"-",并将原文件后缀名加入新文件
      String newName= UUID.randomUUID().toString().replace("-","")
          +oldName.substring(oldName.lastIndexOf("."));
      //建立每一个文件上传的返回参数
      Map<String,Object> map=new HashMap<>();
      //文件保存操作
      try {
        file.transferTo(new File(folder,newName));
        //建立新文件路径,在前端可以直接访问如http://localhost:8080/uploadFile/2021-07-16/新文件名(带后缀)
        String filePath=request.getScheme()+"://"+request.getServerName()+":"+
            request.getServerPort()+"/"+request.getServletContext().getContextPath()+"/uploadFile/"+uploaddate+"/"+newName;
        //写入返回参数
        map.put("oldName",oldName);
        map.put("newName",newName);
        map.put("filePath",filePath);
        listmap.add(map);
      }catch (IOException ex){
        //操作失败报错并写入返回参数
        ex.printStackTrace();
        result.fail(null,ex.getMessage());
        return result;
      }
      result.success(listmap);
    }
    //将执行结果返回
    return result;
  }


  //POST请求接口为/upload
  @ApiOperation(value = "文件上传")
  @PostMapping(value = "/upload", produces = "application/json;charset=utf-8")
  @ResponseBody
  //@RequestParam指向前端input file的name,加入HttpServletRequest请求
  public Result<Object> upload(@RequestParam("uploadFile") MultipartFile file, HttpServletRequest request){
    Result<Object> result = new Result<>();
    //设置当前日期
    String uploaddate= new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    //设置文件上传保存文件路径：保存在项目运行目录下的uploadFile文件夹+当前日期
    String savepath = FileUploadController.filePath+uploaddate;
    //String savepath = request.getSession().getServletContext().getRealPath("/uploadFile/")+uploaddate;
    //创建文件夹,当文件夹不存在时，创建文件夹
    File folder = new File(savepath);
    if(!folder.isDirectory()){
      folder.mkdir();
    }
      //重命名上传的文件,为避免重复,我们使用UUID对文件分别进行命名
      String oldName=file.getOriginalFilename();//getOriginalFilename()获取文件名带后缀
      //UUID去掉中间的"-",并将原文件后缀名加入新文件
      String newName= UUID.randomUUID().toString().replace("-","")
          +oldName.substring(oldName.lastIndexOf("."));
      //建立每一个文件上传的返回参数
      Map<String,Object> map=new HashMap<>();
      //文件保存操作
      try {
        file.transferTo(new File(folder,newName));
        //建立新文件路径,在前端可以直接访问如http://localhost:8080/uploadFile/2021-07-16/新文件名(带后缀)
        String filePath=FileUploadController.domainName+"uploadFile/"+uploaddate+"/"+newName;
        //写入返回参数
        map.put("oldName",oldName);
        map.put("newName",newName);
        map.put("filePath",filePath);
        result.success(map);
      }catch (IOException ex){
        //操作失败报错并写入返回参数
        ex.printStackTrace();
        result.fail(null,ex.getMessage());
      }
    //将执行结果返回
    return result;
  }
}